package graph.paint.text;

import graph.Edge;
import graph.Node;
import graph.paint.NodePainter;
import graph.paint.ViewPort;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;

public class TextPainter implements graph.paint.EdgePainter<String,Object>, NodePainter<String> {

	private int height;
	private int color;

	public TextPainter(int height, int color) {
		this.height = height;
		this.color = color;
	}
	@Override
	public void paint(GC gc, Edge<String,Object> edge, ViewPort viewPort, NodePainter<String> nodePainter) {
		int[] posa = viewPort.viewPos(edge.a.pos.x, edge.a.pos.y);
		int[] posb = viewPort.viewPos(edge.b.pos.x, edge.b.pos.y);
		gc.drawLine(posa[0], posa[1], posb[0], posb[1]);
	}

	@Override
	public void paint(GC gc, ViewPort viewPort, Node<String> node) {
		int[] pos = viewPort.viewPos(node.pos.x, node.pos.y);
		drawText(gc, node.data, pos);
	}

	@Override
	public int[] boundary(GC gc, ViewPort viewPort, Node<String> node,
			double xdir, double ydir) {
		return null;
	}

	private void drawText(GC gc, String string, int[] pos) {
		Font origfont = gc.getFont();
		FontData[] data = origfont.getFontData();
		for (FontData d : data) {
			d.setHeight(height);
		}
		Font font = new Font(origfont.getDevice(), data);
		gc.setFont(font);
		Point p = gc.textExtent(string);
		Color bg = gc.getBackground();
		gc.setBackground(gc.getDevice().getSystemColor(color));
		gc.drawText(string, pos[0]-p.x/2, pos[1]-p.y/2);
		gc.setBackground(bg);
		gc.setFont(origfont);
		font.dispose();
		gc.drawRectangle(pos[0]-p.x/2-1, pos[1]-p.y/2-1, p.x, p.y+1);
	}

}
